<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['goodsExchange:add'])" type="primary"
            @click="handleAddGoodsExchange">新增</el-button>
          <el-button v-if="checkPermission(['goodsExchange:del'])" size="mini" @click="handleDeleteGoodsExchange()"
            type="danger" :disabled="multipleSelection.length === 0">删除</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" placeholder="请输入换货单编号" advanced
            advancedWidth="465">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                <el-form-item label="所属部门">
                  <el-cascader v-model="advancedForm.dept_id" :options="deptList" :props="{
                    label: 'name',
                    value: 'id',
                    emitPath: false,
                    checkStrictly: true
                  }" clearable></el-cascader>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="advancedForm.status">
                    <el-option key="WAIT" label="待审核" value="WAIT" />
                    <el-option key="NEW" label="新创建" value="NEW" />
                    <el-option key="CONFIRMED" label="已确认" value="CONFIRMED" />
                    <el-option key="RETURNED" label="已归还" value="RETURNED" />
                    <el-option key="PASS" label="审核通过" value="PASS" />
                    <el-option key="REJECT" label="审核拒绝" value="REJECT" />
                  </el-select>
                </el-form-item>
                <el-form-item label="服务专员">
                  <el-input v-model="advancedForm.staff_name"></el-input>
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker v-model="advancedForm.goodsExchange_time_range" type="daterange" align="center"
                    :editable="false" unlink-panels :clearable="false" :default-time="['00:00:00', '23:59:59']"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                    :picker-options="{ disabledDate(time) { return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1 }, shortcuts: MixinPickerShortcuts }">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sn" label="换货单编号">
          <template slot-scope="scope">
            <router-link
              v-if="checkPermission(['goodsExchange'])"
              style="color: #409eff;"
              :to="{ name: 'goodsExchangeDetail', params: { id: scope.row.id } }">
              {{ scope.row.sn }}
            </router-link>
            <span v-else>{{scope.row.sn}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="change_time" label="换货日期">
          <template slot-scope="scope">{{ scope.row.change_time | unixToDate }}</template>
        </el-table-column>
        <el-table-column prop="dept_name" label="所属部门" />
        <el-table-column prop="warehouse_name" label="仓库" />
        <el-table-column prop="staff_name" label="服务专员" />
        <el-table-column prop="handled_by" label="登记人" />
        <el-table-column prop="audit_person_name" label="审核人" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">{{ statusFilter(scope.row.status) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="450">
          <template slot-scope="scope">
            <el-button v-if="scope.row.allowable.allow_audit && checkPermission(['goodsExchange:audit'])" type="success"
              size="mini" @click="handleAuditGoodsExchange(scope.row)">审核</el-button>
            <el-button v-if="scope.row.allowable.allow_submit && checkPermission(['goodsExchange:submit'])" type="success"
              size="mini" @click="handleSubmitGoodsExchange(scope.row)">提交</el-button>
            <el-button v-if="scope.row.allowable.allow_cancel && checkPermission(['goodsExchange:withdraw'])" type="danger"
              size="mini" @click="handleCancelGoodsExchange(scope.row)">撤回</el-button>
            <el-button v-if="scope.row.allowable.allow_edit && checkPermission(['goodsExchange:edit'])" size="mini"
              @click="handleEditGoodsExchange(scope.row)">编辑</el-button>
            <el-button v-if="checkPermission(['goodsExchange:print'])" type="primary" size="mini"
              @click="handlePrintGoodsExchangeDialog(scope.row)">打印</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>

    <el-dialog title="换货单表" :visible.sync="dialogVisible" width="940px" center>
      <el-button size="mini" type="primary" @click="handlePrintGoodsExchange" class="print">打印</el-button>
      <div id="deliverySheet" style="width:811px">
        <div class="tips-t">
          <div>
            换货单号:{{ goodsExchangeForm.sn }}
          </div>
          <div>
            换货时间:{{ goodsExchangeForm.change_time | unixToDateStr }}
          </div>
          <div>
            仓库:{{ goodsExchangeForm.warehouse_name }}
          </div>
        </div>
        <div class="tips-t">
          <div>
            所属部门:{{ goodsExchangeForm.dept_name }}
          </div>
          <div>
            登记人:{{ goodsExchangeForm.handled_by }}
          </div>
          <div>
            审核人:{{ goodsExchangeForm.change_person }}
          </div>
        </div>
        <div class="tips-t">
          <div>
            换货说明:{{ goodsExchangeForm.change_desc }}
          </div>
          <div></div>
          <div></div>
        </div>
        <div class="mx">
          <h3>换货商品明细</h3>
        </div>
        <el-table :data="goodsExchangeForm.change_list" border :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }" style=" width:100%;margin-top: 20px;">
          <el-table-column label="批次编号" width="150">
            <template slot-scope="scope">
              {{ scope.row.stock_sn }}
            </template>
          </el-table-column>
          <el-table-column label="商品编号" width="150">
            <template slot-scope="scope">
              {{ scope.row.product_sn }}
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="160">
            <template slot-scope="scope">
              {{ scope.row.product_name }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号" width="170">
            <template slot-scope="scope">
              {{ scope.row.specification }}
            </template>
          </el-table-column>
          <el-table-column label="换货数量" width="90">
            <template slot-scope="scope">
              {{ scope.row.num }}
            </template>
          </el-table-column>
          <el-table-column label="换货金额" width="90">
            <template slot-scope="scope">
              {{ scope.row.amount }}
            </template>
          </el-table-column>
        </el-table>
        <div class="mx">
          <h3>退货商品明细</h3>
        </div>
        <el-table :data="goodsExchangeForm.return_list" border :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }" style=" width:100%;margin-top: 20px;">
          <el-table-column label="批次编号" width="150">
            <template slot-scope="scope">
              {{ scope.row.stock_sn }}
            </template>
          </el-table-column>
          <el-table-column label="商品编号" width="150">
            <template slot-scope="scope">
              {{ scope.row.product_sn }}
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="160">
            <template slot-scope="scope">
              {{ scope.row.product_name }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号" width="170">
            <template slot-scope="scope">
              {{ scope.row.specification }}
            </template>
          </el-table-column>
          <el-table-column label="换货数量" width="90">
            <template slot-scope="scope">
              {{ scope.row.num }}
            </template>
          </el-table-column>
          <el-table-column label="换货金额" width="90">
            <template slot-scope="scope">
              {{ scope.row.amount }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_GoodsExchange from '@/api/goodsExchange'
import Print from 'print-js'
import * as API_Setting from '@/api/setting'
import { Foundation } from '~/ui-utils'
export default {
  name: 'goodsExchange',
  data() {
    return {
      deptList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: '',
      dialogVisible: false,
      // 当前已选择的行
      multipleSelection: [],
      goodsExchangeForm: {}
    }
  },
  mounted() {
    this.GET_GoodsExchangeList()
    this.GET_DeptList()
  },
  watch: {
    $route: function({ query }) {
      this.params.page_no = 1
      this.GET_GoodsExchangeList()
    }
  },
  methods: {
    /** 状态 */
    statusFilter(val) {
      switch (val) {
        case 'WAIT':
          return '待审核'
        case 'NEW':
          return '新创建'
        case 'CONFIRMED':
          return '已确认'
        case 'RETURNED':
          return '已归还'
        case 'COMPLETE':
          return '已完成'
        case 'PASS':
          return '审核通过'
        case 'REJECT':
          return '审核拒绝'
        default:
          return ''
      }
    },
    /** 编辑 */
    handleEditGoodsExchange(row) {
      this.$router.push({
        name: 'goodsExchangeEdit',
        params: { id: row.id }
      })
    },
    /** 提交审核 */
    handleSubmitGoodsExchange(row) {
      API_GoodsExchange.submitAuditGoodsExchange(row.id).then(() => {
        this.$message.success('提交成功！')
        this.GET_GoodsExchangeList()
      })
    },
    /** 撤回审核 */
    handleCancelGoodsExchange(row) {
      API_GoodsExchange.cancelGoodsExchange(row.id).then(() => {
        this.$message.success('撤回成功！')
        this.GET_GoodsExchangeList()
      })
    },
    /** 审核 */
    handleAuditGoodsExchange(row) {
      this.$router.push({
        name: 'goodsExchangeAudit',
        params: {
          id: row.id
        }
      })
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    /** 打印对账详情 */
    handlePrintGoodsExchange() {
      Print({
        printable: 'deliverySheet',
        type: 'html',
        targetStyles: ['*'],
        ignoreElements: ['no-logs', 'goods-image', 'no-btn']
      })
    },
    handleDeleteGoodsExchange() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定要删除这些换货单吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_GoodsExchange.deleteGoodsExchange(ids).then(() => {
          this.$message.success('删除成功！')
          this.GET_GoodsExchangeList()
        })
      }).catch(() => { })
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      console.log('val=-', val)
      this.multipleSelection = val
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_GoodsExchangeList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_GoodsExchangeList()
    },

    /** 添加换货单 */
    handleAddGoodsExchange() {
      this.$router.push({
        name: 'goodsExchangeAdd',
        params: { callback: this.GET_GoodsExchangeList }
      })
    },
    /** 打印换货单 */
    handlePrintGoodsExchangeDialog(row) {
      this.GET_GoodsExchangeDetail(row.id)
    },
    /** 获取换货单详情页面数据 */
    GET_GoodsExchangeDetail(id) {
      API_GoodsExchange.getGoodsExchangeInfo(id).then(response => {
        this.goodsExchangeForm = response
        if (response.change_list && response.change_list.length) {
          var str = ''
          response.change_list.forEach(function(i) {
            str += i.product_name + '、'
          })
        }
        this.goodsExchangeForm.illustrate = str
        this.dialogVisible = true
      })
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data
      }
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key])
      this.params.page_no = 1
      this.GET_GoodsExchangeList()
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.goodsExchange_time_range) {
        this.params.start_time = parseInt(Number(this.advancedForm.goodsExchange_time_range[0]) / 1000)
        this.params.end_time = parseInt(Number(this.advancedForm.goodsExchange_time_range[1]) / 1000)
      }
      delete this.params.goodsExchange_time_range
      this.params.page_no = 1
      this.GET_GoodsExchangeList()
    },
    /** 获取换货单列表 */
    GET_GoodsExchangeList() {
      this.loading = true
      API_GoodsExchange.getGoodsExchangeList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.print {
  margin-left: 790px;
}

.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    text-align: left;
    padding-left: 70px;
  }
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
